package com.dap.dubbo.rpc.filter;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.rpc.*;

import com.dap.dubbo.rpc.config.RedisConfig;
import org.mvel2.MVEL;
import org.mvel2.compiler.ExpressionCompiler;
import redis.clients.jedis.Jedis;

/*@Activate(group = Constants.CONSUMER)*/
public class MockFilter  implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Jedis jedis = RedisConfig.getJedis();

        String application = invoker.getUrl().getParameter(Constants.APPLICATION_KEY);
        String interfaceName  =  invoker.getUrl().getParameter(Constants.INTERFACE_KEY);

        invoker.getUrl().getParameter(Constants.APPLICATION_KEY);
        //从dubbo的URL中读取mock信息，是否需要mock
        String mockValue = invoker.getUrl().getParameter(invocation.getMethodName()+"."+Constants.MOCK_KEY);
        if (StringUtils.isBlank(mockValue)) {
            mockValue = invoker.getUrl().getParameter(Constants.MOCK_KEY);
        }
        //从Redis中查询接口信息，是不是需要mock
        if(StringUtils.isBlank(mockValue) && null!=jedis){
            String mockKey = "FOP:Mock_"+ invoker.getUrl().getParameter("group");
            String mockField = "MOCK_FUN";
            mockValue=jedis.hget(mockKey,mockField);
            jedis.close();
        }
        if(!StringUtils.isBlank(mockValue) ){
            if("y".equals(mockValue)){
               /* ExpressionCompiler compiler = new ExpressionCompiler("11111");
                org.mvel2.compiler.CompiledExpression exp = compiler.compile();
                Object result = MVEL.executeExpression(exp);*/
               //TODO result值的类型必须与接口返回值类型一致
                System.out.println("111");

                return new RpcResult("111");
            }
     }
     return invoker.invoke(invocation);
    }
}
